package com.qire.manhua.dal.service;

import com.qire.antsbinder.dal.DataService;
import com.qire.common.concurrent.Scheduler;
import com.qire.common.concurrent.ThreadUtil;
import com.qire.common.utils.FileManager;
import com.qire.manhua.dal.dao.ComicChapterDao;
import com.qire.manhua.dal.dao.ComicDatabase;
import com.qire.manhua.model.po.LocalComicChapter;
import com.qire.manhua.model.viewModel.impl.ComicDownloadProgressViewModel;

import java.util.List;

public class ComicDownloadProgressService extends DataService {

    private final ComicChapterDao comicChapterDao = ComicDatabase.database().comicChapterDao();

    private final ComicDownloadProgressViewModel viewModel;

    public ComicDownloadProgressService(ComicDownloadProgressViewModel viewModel) {
        this.viewModel = viewModel;
    }

    public void loadComicChapter() {
        ThreadUtil.once().andThen(data -> {
            List<LocalComicChapter> comicChapterList = comicChapterDao.queryListBy(viewModel.comicBookId());
            viewModel.progressListClear();
            for(LocalComicChapter chapter : comicChapterList) {
                viewModel.addProgressItem(chapter);
            }
        }).schedulerBy(Scheduler.Main).andThen(data -> {
            viewModel.refreshUI();
            viewModel.refreshAdapter();
        }).accept();
    }

    public void batchDeleteDownloadRecord(LocalComicChapter... comicChapters) {
        ThreadUtil.<LocalComicChapter[]>once().map(comicChapters).andThen(deleteList -> {
            // 删除数据库记录
            comicChapterDao.delete(deleteList);
            // 删除本地下载文件目录
            for(LocalComicChapter chapter : deleteList) {
                FileManager.deleteChapterFolder(chapter.getComicId(), chapter.getId());
            }
        }).accept();
    }

}
